<template>
  <section>
    <div class="content-title">{{ title }}</div>
    <div class="color">
      <div class="controls">
        <div><input type="color" v-model="hexColor" /></div>
        <!-- <div><el-color-picker v-model="hexColor" /></div> -->
        <div> {{ hexColor }}</div>
        <div> {{ rgbColor }}</div>
      </div>
      <div class="btns">
        <div><el-button type="warning" @click="randomColor"> 随机色 </el-button></div>
        <div><el-button type="primary" @click="copyHex"> 复制HEX </el-button></div>
        <div><el-button type="success" @click="copyRgb"> 复制RGB</el-button></div>
      </div>
    </div>
  </section>
</template>
<script setup>
import { ref, inject } from 'vue';
const global = inject('global')
const hexColor = ref('#000000')
const rgbColor = ref('')
const colors = ref([0, 0, 0])
const props = defineProps({
  title: {
    type: String,
    defalut: ''
  }
})
function copyHex() {
  navigator.clipboard.writeText(hexColor.value).then(() => {
    global.success('复制HEX成功')
  })
}

function copyRgb() {
  navigator.clipboard.writeText(rgbColor.value).then(() => {
    global.success('复制RGB成功')
  })
}
function mathFloor() {
  return Math.floor(Math.random() * 256) // 生成0到255之间的随机数
}

function rgbToHex(rgb) {
  // // console.log(rgb)
  // 将 RGB 字符串分割成三个数字
  const [r, g, b] = rgb.match(/\d+/g).map(Number);

  // 将每个数字转换为十六进制，并补零到两位
  const hexR = r.toString(16).padStart(2, '0');
  const hexG = g.toString(16).padStart(2, '0');
  const hexB = b.toString(16).padStart(2, '0');

  // 返回十六进制颜色代码
  return `#${hexR}${hexG}${hexB}`;
}
function randomColor() {
  colors.value[0] = mathFloor()
  colors.value[1] = mathFloor()
  colors.value[2] = mathFloor()
  rgbColor.value = 'rgba(' + colors.value.join(',') + ')'
  hexColor.value = rgbToHex(rgbColor.value)
}
</script>
<style scoped lang="scss">
.controls{
  display: flex;
  justify-content: space-around;
  >div{
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
  >div:nth-child(1){width: 50px;}
  >div:nth-child(2){width: 50px;}
  >div:nth-child(3){width: 80px;}
  >div:nth-child(4){width: 120px;}
}
.btns{
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}
</style>
